package com.qf.shiro;

import com.qf.pojo.DtsAdmin;
import com.qf.service.DtsAdminService;
import com.qf.service.DtsPermissionService;
import com.qf.service.DtsRoleService;
import com.qf.util.AdminResponseCode;
import com.qf.util.AdminResponseUtil;
import com.qf.util.bcrypt.BCryptPasswordEncoder;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

/**
 * @author Zwnan
 */
public class AdminAuthorizingRealm extends AuthorizingRealm {

    @Autowired
    private DtsAdminService dtsAdminService;

    @Autowired
    private DtsRoleService dtsRoleService;

    @Autowired
    private DtsPermissionService dtsPermissionService;


    /**
     * 授权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //1.角色对象
        DtsAdmin dtsAdmin = (DtsAdmin) principalCollection.getPrimaryPrincipal();
        //对象集合
        Set<String> roles = dtsRoleService.findByIds(dtsAdmin.getRoleIds());

        //权限集合
        Set<String> perms = dtsPermissionService.findpermissionByRoleIds(dtsAdmin.getRoleIds());

        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.setRoles(roles);
        simpleAuthorizationInfo.setStringPermissions(perms);

        return simpleAuthorizationInfo;
    }

    /**
     * 认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) authenticationToken;
        String username = usernamePasswordToken.getUsername();
        String password = new String(usernamePasswordToken.getPassword());
        DtsAdmin dtsAdmin = dtsAdminService.findByUsername(username);
        System.out.println(dtsAdmin.toString());
        if (null == dtsAdmin){
            throw new AuthenticationException();
        }
        if (!new BCryptPasswordEncoder().matches(password, dtsAdmin.getPassword())){
            throw new IncorrectCredentialsException();
        }
        Boolean deleted = dtsAdmin.getDeleted();
        if (deleted){
            throw  new LockedAccountException();
        }

        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(dtsAdmin, password, this.getName());
        return simpleAuthenticationInfo;
    }
}
